const Service = require('egg').Service;
const { OpenAI } = require('openai');

class Openai302Service extends Service {
  constructor(ctx) {
    super(ctx);
    const config = this.config.openai302;
    console.log('config',config)
    this.client = new OpenAI({
      apiKey: config.apiKey,
      baseURL: config.apiUrl,
      timeout: 60000,
      maxRetries: 2,
    });
  }

  async chatCompletion(messages, model) {
    const startTime = Date.now();

    try {
      // 记录请求信息
      this.ctx.logger.info('[DeepSeek] Request started', {
        model: model,
        messageCount: messages.length
      });
      console.log('messages',{
        model,
        messages,
        // stream: true,
      })

      let stream  = await this.client.chat.completions.create({
        model,
        messages,
        stream: true,
      });
      console.log('stream',stream)
      const duration = Date.now() - startTime;
      this.ctx.logger.info('[Chat] Request completed', {
        duration,
        model,
        status: 'success'
      });

      return stream;

    } catch (error) {
      const duration = Date.now() - startTime;
      this.ctx.logger.error('[Chat] Request failed', {
        duration,
        error: {
          name: error.name,
          message: error.message,
          code: error.code,
          type: error.type,
          status: error.status,
          details: error.details
        }
      });
      throw error;
    }
  }
  async chatCompletionSync(messages, model) {
    return this.client.chat.completions.create({
      model,
      messages,
      stream: false,
    });
  }
}

module.exports = Openai302Service;
